I must Write a program using getchar() function only to read the character string from the keyboard until ‘.’ is terminated, then reverse the string and display result on on the screen.
I don't know why but my program doesn't run right. Can anyone help me, pls. And this is my code:
Code:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
main()
{
unsigned int choice, i, j, n;
char c, temp;
char s1[100], s2[100];
while(1){
do{
system("cls");
printf("Choose one of the following options: ");
printf("\n1. Input a string");
printf("\n2. Dislay a string");
printf("\n3. Reverse a string");
printf("\n0. Exit");
printf("\nYour selection (0 -> 3): ");
scanf("%d", &choice);}
while(choice<0 || choice>3);
switch(choice){
case 1: printf("\nEnter string ended by . : ");
for(i=0; (c=getchar()) != '.'; i++) s1[i]=c;
n=strlen(s1);
for(i=0;i<n;i++)
if (s1[i]=='\n')
{
for(j=i;j<n;j++) s1[j]=s1[j+1];
s1[n--]='\0';
i--;
}
strcpy(s2,s1);
system("pause");
break;
case 2: printf("String entered is \" ");
for(i=0;i<n;i++) printf("%c", s1[i]);
printf(" \" \n");
system("pause");
break;
case 3: for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
{
temp=s2[i];
s2[i]=s2[j];
s2[j]=temp;
};
printf("The orginal string: ");
for(i=0;i<n;i++) printf("%c", s1[i]);
printf("\n");
printf("The reverse string: ");
for(i=0;i<n;i++) printf("%c", s2[i]);
printf("\n");
system("pause");
break;
case 0: exit(0);}}
}